package org.cuatrovientos.erp.dao;


/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Employee;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


/**
 *
 * @author CaselHunter
 *
 */
public class EmployeeDAO implements EmployeeDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public EmployeeDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one employee by Id
	 * @param id
	 * @return employee
	 */
	 @Transactional(readOnly = true)
	public Employee selectById(int id) {
		Employee employee = (Employee) getSession().get(Employee.class, id);
	    return employee;
	}

	/*
	 * retrieves all employees from db
	 * @return List of employees
	 */
	 @Transactional(readOnly = true)
	public List<Employee> selectAll() {
	 
	    List<Employee> employees = getSession().createQuery("from Employee").list();
	    return employees;
	}
	
	/*
	 * retrieves all employees from db
	 * @return List of employees
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Employee> employees = getSession().createQuery("from Employee").list();
	    return employees.size();
	}

	/*
	 * inserts a new employee in database
	 * retrieves generated id and sets to employee instance
	 * @param new employee
	 */
	 @Transactional
	public void insert(Employee employee) {
	    Integer id = (Integer) getSession().save(employee);
	    employee.setId(id);           
	}

	/*
	 * updates employee
	 * @param employee to update
	 */
	 @Transactional
	public void update(Employee employee) {
		getSession().merge(employee);
	}

	/*
	 * delete given employee
	 * @param employee to delete
	 */
	 @Transactional
	public void delete(Employee employee) {
		getSession().delete(employee);
	}

	 @Transactional
	public void saveOrUpdate(Employee employee) {

		getSession().saveOrUpdate(employee);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Employee employee = (Employee) getSession().load(Employee.class,id);
		 getSession().delete(employee);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Employee> search(String name) {
		   Query query = getSession().createQuery("from Employee employee where employee.name like :name");
           query.setParameter("description", "%"+name+"%");
           
           List<Employee> employees = query.list();
		
           return employees;
	}

}
